package com.sali.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sali.config.ReturnModel;
import com.sali.entity.MockVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * @description:
 * @author: sali
 * @date: 2025/2/20 上午12:12.
 * @version: 1.0
 */
@RestController
@RequestMapping(value = "/mock/receiver")
@Slf4j
public class HttpMockReceiver {

    private static final String DELETE_METHOD = "delete";
    private static final String MOCK_ID_KEY = "mockId";

    @PostMapping("/api/1")
    @ResponseBody
    public Object httpReceive(@RequestParam(value = "method", required = false) String method, @RequestBody JSONObject jsonObject) {
        log.info("接收到的数据为:{}", jsonObject);
        if (DELETE_METHOD.equals(method) && jsonObject.containsKey(MOCK_ID_KEY)) {
            JSONArray jsonArray = jsonObject.getJSONArray(MOCK_ID_KEY);
            if (!jsonArray.isEmpty()) {
                return ReturnModel.getInstance().ok();
            } else {
                return ReturnModel.getInstance().error();
            }
        } else {
            try {
                MockVO ruleVO = JSONUtil.toBean(jsonObject, MockVO.class);
                if (ruleVO.getMockIds() != null && ruleVO.getMockIds().length > 0) {
                    return ReturnModel.getInstance().ok();
                } else {
                    return ReturnModel.getInstance().error();
                }
            } catch (JSONException e) {
                return ReturnModel.getInstance().error();
            }
        }
    }

}
